<?php

declare(strict_types=1);

namespace App\Job;

use App\Constants\CacheKey;
use App\Model\ChatInfo;
use App\Services\Formatter\ChatFormatter;
use App\Services\MeetingService;
use Hyperf\AsyncQueue\Job;
use Hyperf\Redis\Redis;
use Hyperf\Snowflake\IdGenerator;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Utils\Codec\Json;
use Hyperf\Di\Annotation\Inject;

class ChatJob extends Job
{
    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     * @var int
     */
    protected $maxAttempts = 3;

    /**
     * 数据
     * @var array
     */
    public $params;

    /**
     * @Inject
     * @var MeetingService
     */
    public $meetingService;

    /**
     * @Inject
     * @var ChatFormatter
     */
    public $formatter;

    public function __construct(array $params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        $data = $this->params;
        $model = new ChatInfo();
        $fill['id'] = di()->get(IdGeneratorInterface::class)->generate();
        $redis = di()->get(Redis::class);
        if (!isset($data['token'])) {
            $fill['sender_id'] = $data['senderId'] ?? -1;
            $fill['sender_name'] = $data['senderName'] ?? '';
        } else {
            $key = CacheKey::USER_AUTH_KEY . $data['token'];
            if ($redis->exists($key)) {
                $user = Json::decode($redis->get($key));
                $fill['sender_name'] = $user['nickname'];
                $fill['sender_id'] = $user['userId'];
            }
        }
        if (isset($data['meetingId']) && $data['meetingId'] > 0) {
            $fill['meeting_id'] = $data['meetingId'];
            $fill['recv_id'] = 0;
        }
        $fill['content'] = $data['content'] ?? '';
        $fill['msg_type'] = $data['msgType'] ?? 0;
        $fill['send_time'] = $data['sendTime'] ?? date('Y-m-d H:i:s');

        $meeting = $this->meetingService->findInfoById((int)$data['meetingId']);
        $meetingUser = $meeting['userId'] ?? 0;
        $model = $model->fill($fill);
        $model->save();
//        $redis->lPush(sprintf(CacheKey::MEETING_GROUP_MSG_LIST, $data['meetingId']),
//            Json::encode($this->formatter->stdoutFormatter($model, $meetingUser)));
    }
}
